<template>
  <div style="background-image:linear-gradient(45deg,#a3bded 0%, #6991c7 100%);overflow: hidden">
      <div style="position: fixed;background-image:linear-gradient(-225deg,#7DE2FC 0%, #B9B6E5 100%);
      height: 50px;line-height: 50px;left: 0;right: 0;text-align: right;z-index: 30;overflow: hidden">
        <span style="color: red;display: inline-block;">剩余考试时间:{{timeH}}时{{timeM}}分{{timeS}}秒</span>
        <el-button type="primary" size="medium" style="margin-right: 100px;margin-left: 20px" round @click="openSubmitExam()">交卷</el-button>
      </div>
      <div style="width: 1000px;background-color: white;height: 100%;margin: 30px auto">
        <div style="padding: 10px">
          <h1 style="color: black;margin-top: 30px">{{this.examQuestionStart.examName}}</h1>
        </div>
        <el-divider><i class="el-icon-document"></i>考试开始</el-divider>
        <div v-for="(item,index) in examQuestionStart.questions" :key="item.id" style="text-align: left;padding-left: 30px">
          <div v-if="item.quType==1" style="margin: 10px">
            <i  class="el-icon-collection-tag"></i>{{index+1}}、{{item.quContent}}(单选题 {{item.scores}}分)
            <div v-for="(qs,qIndex) in item.allOption.split('￥&')" :key="qIndex" style="padding: 5px;margin-left:20px ">
              <el-radio v-model="answers[index]" :label="qs">{{qs}}</el-radio>
            </div>
          </div>
          <div v-if="item.quType==2" style="margin: 10px">
            <i class="el-icon-collection-tag"></i>{{index+1}}、{{item.quContent}}(多选题 {{item.scores}}分)
              <label   v-for="(qs,qIndex) in item.allOption.split('￥&')" :key="qIndex" style="display: block;margin: 10px 25px">
                <input type="checkbox" :value="qs" v-model="answers[index]">
                {{qs}}
              </label>
          </div>
          <div v-if="item.quType==3" style="margin: 10px">
            <i class="el-icon-collection-tag"></i>{{index+1}}、{{item.quContent}}(判断题 {{item.scores}}分)
            <div v-for="(qs,qIndex) in item.allOption.split('￥&')" :key="qIndex" style="padding: 5px;margin-left:20px ">
              <el-radio v-model="answers[index]" :label="qs">{{qs}}</el-radio>
            </div>
          </div>
          <div v-if="item.quType==4" style="margin: 20px 10px">
            <i class="el-icon-collection-tag"></i>{{index+1}}、{{item.quContent}}(简答题 {{item.scores}}分)
            <div>
              <el-input
                  type="textarea"
                  placeholder="请输入内容"
                  v-model="answers[index]"
                  style="height:auto;margin-top: 10px"
                  show-word-limit></el-input>
            </div>
          </div>
        </div>
        <el-divider><i class="el-icon-document"></i>考试结束</el-divider>
        <div style="height: 50px"></div>
      </div>
  </div>
</template>

<script>
export default {
  data(){
    return{
      dingshi:'',
      examId:'',
      examQuestionStart:{},
      answers:[],
      timeStartTime:0,
      timeH:0,
      timeM:0,
      timeS:0,
    }
  },
  methods:{
    startTimer() {
      this.dingshi = setInterval(() => {
        this.timeS--;
        if(this.timeS<0){
          this.timeM--;
          this.timeS = 59;
          if(this.timeM<0){
            this.timeM = 59;
            this.timeH--;
            if(this.timeH<0){
              this.submitExam();
            }
          }
        }
        localStorage.setItem("timeH",this.timeH);
        localStorage.setItem("timeM",this.timeM);
        localStorage.setItem("timeS",this.timeS);
      }, 1000);
    },
    openSubmitExam(){
      let boolean = true;
      for (let i = 0; i < this.answers.length; i++) {
        if(this.answers[i]==null||this.answers[i].length==0||this.answers[i]==""){
          boolean = false;
        }
      }
      let message = ""
      if(boolean){
        message = '试卷提交后无法更改, 是否继续?'
      }else {
        message = "您还有题目未填写是否提交?"
      }
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submitExam();
      }).catch(() => {
      });
    },
    submitExam(){
      let qs = this.examQuestionStart.questions;
      console.log(qs)
      let questionAnswers = [];
      for (let i = 0; i < qs.length; i++) {
        let q = {
          questionId:qs[i].id,
          answer:''
        }
        if(this.answers[i].length!=0){
          if(qs[i].quType==2){
            for (let j = 0; j < this.answers[i].length; j++) {
              q.answer +=this.answers[i][j].substring(0,1)+",";
            }
            q.answer = q.answer.substring(0,q.answer.length-1);
          }else if(qs[i].quType==4){
            q.answer = this.answers[i];
          }else {
            q.answer = this.answers[i][0].substring(0,1);
          }
        }
        questionAnswers.push(q);
      }
      let localUser = JSON.parse(localStorage.getItem("localUser"));
      let param = {
        userId:localUser.id,
        examId:this.examId,
        questionAnswers:questionAnswers
      }
     //提交给服务器处理数据

      let url = "http://localhost:9283/examRecord/add-new/";
      let jwt = localStorage.getItem("localJwt");
      this.axios
          .create({
            'headers':{
              'Authorization':jwt
            }
          }).post(url,param).then((response)=> {
        let jsonResult = response.data;
        if(jsonResult.state==20000){
          this.$message({
            showClose: true,
            message: '交卷成功',
            type: 'success'
          });
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
      clearInterval(this.dingshi)
      let t = localStorage.getItem("timeM");
      console.log(t==null)
      localStorage.removeItem("timeH")
      localStorage.removeItem("timeM")
      localStorage.removeItem("timeS")
      this.$router.push('/student')
    },
    LoadExamId(){
      this.examId = this.$router.currentRoute.query.examId;
      let url = "http://localhost:9283/exam/getExamQuestions/"+this.examId;
      let jwt = localStorage.getItem("localJwt");
      this.axios
          .create({
            'headers':{
              'Authorization':jwt
            }
          }).get(url).then((response)=> {
        let jsonResult = response.data;
        if(jsonResult.state==20000){
          this.examQuestionStart = jsonResult.data;
          let answers = [];
          for (let i = 0; i < this.examQuestionStart.questions.length; i++) {
            let q = []
            if(this.examQuestionStart.questions[i].quType==4){
              q = '';
            }
            answers.push(q);
          }
          this.answers = answers;
          localStorage.setItem("answersByStudent",JSON.stringify(this.answers));
          console.log(this.answers)
          localStorage.setItem("examQuestionStart",JSON.stringify(this.examQuestionStart));
          let timeStartTime = this.examQuestionStart.duration;
          this.timeH = Math.trunc(timeStartTime/60);
          this.timeM = timeStartTime - this.timeH *60;
          this.timeS = 0;
          localStorage.setItem("timeH",this.timeH);
          localStorage.setItem("timeM",this.timeM);
          localStorage.setItem("timeS",this.timeS);
          this.startTimer();
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }else if(jsonResult.state==80100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.answers=JSON.parse(localStorage.getItem("answersByStudent"));
          console.log(this.answers)
          this.examQuestionStart=JSON.parse(localStorage.getItem("examQuestionStart"));
          console.log(this.examQuestionStart)
          this.timeH=localStorage.getItem("timeH");
          this.timeM= localStorage.getItem("timeM");
          this.timeS = localStorage.getItem("timeS");
          this.startTimer();
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })



    }
  },
  mounted() {
    this.LoadExamId();

  }
}
</script>
